import React, { useRef, useEffect } from "react";
import ReactECharts from "echarts-for-react";
import * as echarts from "echarts";
import $ from "jquery";
import * as turf from "@turf/turf";

// import "./Chart11.less";

const publicUrl = "https://geo.datav.aliyun.com/areas_v3/bound/";

function Chart11() {
  const myChart = useRef(null);

  const data = [
    { name: "上海", value: 42 },
    { name: "鄂尔多斯", value: 25 },
    { name: "招远", value: 23 },
    { name: "舟山", value: 12 },
    { name: "齐齐哈尔", value: 8 },
    { name: "盐城", value: 6 },
    { name: "赤峰", value: 6 },
    { name: "青岛", value: 3 },
  ];
  const geoCoordMap = {
    上海: [121.48169, 31.234694],
    鄂尔多斯: [109.781327, 39.608266],
    招远: [120.38, 37.35],
    舟山: [122.207216, 29.985295],
    齐齐哈尔: [123.97, 47.33],
    盐城: [120.13, 33.38],
    赤峰: [118.87, 42.28],
    青岛: [120.33, 36.07],
  };

  const convertData = (data) => {
    let res = [];
    for (let i = 0; i < data.length; i++) {
      let geoCoord = geoCoordMap[data[i].name];
      if (geoCoord) {
        res.push({
          name: data[i].name,
          value: geoCoord.concat(data[i].value),
        });
      }
    }
    return res;
  };

  useEffect(() => {
    initChart();
  }, []);

  async function initChart() {
    let chart = myChart.current.getEchartsInstance();
    let allAdcode = await getGeoJson("all.json");
    let chinaGeoJson = await getGeoJson("100000_full.json");
    initEcharts(chinaGeoJson, "全国", chart, allAdcode);
  }

  function isPointInMaps(p, mapJson) {
    const areas = mapJson.features;
    let flag = false;
    let targetCoords = turf.point(p);
    for (var i = 0; i < areas.length; i++) {
      var feature = areas[i];
      if (turf.booleanPointInPolygon(targetCoords, feature)) {
        flag = true;
        break;
      }
    }
    return flag;
  }

  function initEcharts(geoJson, name, chart, allAdcode) {
    // let targetCoords = turf.point([109.781327, 39.608266, 2]);
    // for (var i = 0; i < geoJson.features.length; i++) {
    //   var feature = geoJson.features[i];
    //   if (turf.booleanPointInPolygon(targetCoords, feature)) {
    //     console.log(true, targetCoords);
    //     break;
    //   }
    // }

    // console.log(
    //   "%c 🍊 convertData(data): ",
    //   "font-size:20px;background-color: #ED9EC7;color:#fff;",
    //   convertData(data)
    // );

    echarts.registerMap(name, geoJson);

    // const test = convertData(data).filter((item) => {
    //   return isPointInMaps(item.value, geoJson);
    // });
    // console.log(
    //   "%c 🥫 test: ",
    //   "font-size:20px;background-color: #33A5FF;color:#fff;",
    //   test
    // );

    let option = {
      // title: {
      //   text: name,
      //   left: "center",
      // },
      geo: {
        map: name, //地图为刚刚设置的China
        zoom: 1.2,
        // itemStyle: {
        //   //地图区域的多边形 图形样式
        //   // normal: {
        //   areaColor: "#013C62", //地区颜色
        //   //   shadowColor: "#182f68", //阴影颜色
        //   //   shadowOffsetX: 0, //阴影偏移量
        //   //   shadowOffsetY: 25, //阴影偏移量
        //   // },
        //   emphasis: {
        //     areaColor: "#2AB8FF", //地区颜色
        //     label: {
        //       show: false, //是否在高亮状态下显示标签
        //     },
        //   },
        // },
      },
      visualMap: {
        right: "2%",
        bottom: "3%",
        align: "right",
        itemSymbol: "rect",
        seriesIndex: 0,
        min: 0,
        max: 1000,
        // calculable: true,
        pieces: [
          { min: 1500, color: "grey" }, // 不指定 max，表示 max 为无限大（Infinity）。
          { min: 900, max: 1500 },
          { min: 310, max: 1000 },
          { min: 200, max: 300 },
          { min: 10, max: 200, label: "10 到 200（自定义label）" },
          // { value: 123, label: "123（自定义特殊颜色）", color: "grey" }, // 表示 value 等于 123 的情况。
          { max: 5 }, // 不指定 min，表示 min 为无限大（-Infinity）。
        ],
        inRange: {
          color: ["#50a3ba", "#eac736", "#d94e5d"],
        },
      },

      series: [
        {
          name: "map",
          type: "map",
          map: name,
          zoom: 1.2,
          // roam: true,
          itemStyle: {
            show: true,
            areaColor: "#0a0a1f",
            borderColor: "#5a5a89",
            borderWidth: "1",
          },
          data: [
            { name: "北京市", value: 100 },
            { name: "上海市", value: 200 },
            { name: "广东省", value: 300 },
            // 其他数据
          ],
        },
        {
          name: "scatter",
          type: "scatter",
          coordinateSystem: "geo",
          data: convertData(data).filter((item) => {
            return isPointInMaps(item.value, geoJson);
          }),
          symbolSize: (val) => {
            const value = val[2];
            if (value >= 25) {
              return 40;
            } else if (value >= 16) {
              return 25;
            } else if (value < 16) {
              return 16;
            }
          },
          itemStyle: {
            color: new echarts.graphic.RadialGradient(0.3, 0.3, 1, [
              {
                offset: 0,
                color: "rgb(251, 118, 123)",
              },
              {
                offset: 1,
                color: "rgb(204, 46, 72)",
              },
            ]),
          },
          encode: {
            value: 2,
          },
          label: {
            formatter: (item) => {
              return item.value[2] >= data[4].value ? item.value[2] : "";
            },
            position: "inside",
            show: true,
            fontSize: 10,
            offset: [0, 1],
          },
        },
      ],
    };

    chart.setOption(option);
    // 解绑click事件
    chart.off("click");
    //给地图添加监听事件
    chart.on("click", (params) => {
      let clickRegion = allAdcode.filter(
        (areaJson) => areaJson.name === params.name
      )[0];

      let clickRegionCode = clickRegion?.adcode;
      let clickRegionLevel = clickRegion?.level;

      (clickRegionLevel == "district"
        ? getGeoJson(`${clickRegionCode}.json`)
        : getGeoJson(`${clickRegionCode}_full.json`)
      )
        .then((regionGeoJson) =>
          initEcharts(regionGeoJson, params.name, chart, allAdcode)
        )
        .catch((err) => {
          getGeoJson("100000_full.json").then((chinaGeoJson) =>
            initEcharts(chinaGeoJson, "全国", chart, allAdcode)
          );
        });
    });
  }
  //获取地图json数据
  async function getGeoJson(jsonName) {
    return await $.get(`${publicUrl}${jsonName}`);
  }

  return (
    <>
      <div
        className="branch-list-bar-container"
        style={{ background: "#5a5a89" }}
      >
        <ReactECharts
          ref={myChart}
          option={{}}
          className="branch-list-bar"
          // onEvents={{ click: onChartClick }}
        />
      </div>
    </>
  );
}

export default Chart11;
